package com.b1502.store2.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.b1502.store2.R;
import com.b1502.store2.model.Category;
import com.b1502.store2.util.ImageLoaderUtils;
import com.b1502.store2.util.UrlUtil;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 作者：张宏达
 * 类的创建时间： 2017/2/27 20:45
 * 类的作用：做分类页面recyclerview的适配器类
 */

public class CategoryFragmentAdapter extends RecyclerView.Adapter<CategoryFragmentAdapter.CategoryViewHolder> {

    //声明变量
    Item item;
    Context context;
    Category[] categories;
    LayoutInflater inflater;
    DisplayImageOptions DisplayImageOptions;

    public CategoryFragmentAdapter(Context context) {
        this.context = context;
        DisplayImageOptions = ImageLoaderUtils.initOptions();
    }


    //添加数据的方法
    public void addData(Category[] categories) {

        this.categories = categories;
        inflater = LayoutInflater.from(context);
    }

    /*
    * 使用接口回调做recyclerview的条目点击事件
    * 声明的接口
    **/
    public interface Item {
        void onClick(int position);
    }

    /*
    * 使用接口的回调方法
    **/
    public void setListener(Item item) {
        this.item = item;
    }

    @Override
    public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.item_category, parent, false);
        CategoryViewHolder holder = new CategoryViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(CategoryViewHolder holder, final int position) {

        //设置条目内容
        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.displayImage(UrlUtil.getImageUrl(categories[position].getImagePath()), holder.item_category_iv, DisplayImageOptions);
        holder.item_category_tv.setText(categories[position].getName());

        //设置条目点击
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                item.onClick(position);
            }
        });

    }


    @Override
    public int getItemCount() {
        return categories.length;
    }


    public class CategoryViewHolder extends RecyclerView.ViewHolder {

        //声明条目中的控件
        ImageView item_category_iv;
        TextView item_category_tv;

        public CategoryViewHolder(View itemView) {
            super(itemView);

            //初始化条目控件
            item_category_iv = (ImageView) itemView.findViewById(R.id.item_category_iv);
            item_category_tv = (TextView) itemView.findViewById(R.id.item_category_tv);
        }
    }
}
